#!/bin/bash
# Create video from PNG sequence using FFmpeg

# Default values
INPUT_DIR="../run_scripts/output/visualization"
OUTPUT_FILE="dragonfly_simulation.mp4"
FPS=10

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -i|--input)
            INPUT_DIR="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_FILE="$2"
            shift 2
            ;;
        -f|--fps)
            FPS="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: $0 [-i INPUT_DIR] [-o OUTPUT_FILE] [-f FPS]"
            echo "  -i, --input    Input directory with PNG files (default: ../../output/visualization)"
            echo "  -o, --output   Output video file (default: dragonfly_simulation.mp4)"
            echo "  -f, --fps      Frames per second (default: 10)"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

echo "======================================================"
echo "Creating video from dragonfly simulation frames"
echo "======================================================"
echo "Input directory: $INPUT_DIR"
echo "Output file: $OUTPUT_FILE"
echo "Frame rate: $FPS fps"
echo "======================================================"

# Check if input directory exists
if [ ! -d "$INPUT_DIR" ]; then
    echo "Error: Input directory '$INPUT_DIR' does not exist"
    exit 1
fi

# Count PNG files
PNG_COUNT=$(ls -1 "$INPUT_DIR"/scene_*.png 2>/dev/null | wc -l)
if [ $PNG_COUNT -eq 0 ]; then
    echo "Error: No scene_*.png files found in $INPUT_DIR"
    exit 1
fi

echo "Found $PNG_COUNT frames"

# Check if FFmpeg is installed
if ! command -v ffmpeg &> /dev/null; then
    echo "Error: FFmpeg is not installed"
    echo "Install it with:"
    echo "  Ubuntu/Debian: sudo apt-get install ffmpeg"
    echo "  macOS: brew install ffmpeg"
    echo "  Other: Visit https://ffmpeg.org/download.html"
    exit 1
fi

# Create video
echo "Creating video..."
ffmpeg -y -framerate $FPS -pattern_type glob -i "$INPUT_DIR/scene_*.png" \
    -c:v libx264 -pix_fmt yuv420p -crf 23 \
    -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" \
    "$OUTPUT_FILE" 2>&1 | grep -E "frame=|fps=|time=|speed="

# Check if successful
if [ $? -eq 0 ]; then
    # Get video info
    DURATION=$(ffmpeg -i "$OUTPUT_FILE" 2>&1 | grep Duration | cut -d ' ' -f 4 | sed s/,//)
    SIZE=$(ls -lh "$OUTPUT_FILE" | awk '{print $5}')
    
    echo ""
    echo "✓ Video created successfully!"
    echo "  File: $OUTPUT_FILE"
    echo "  Duration: $DURATION"
    echo "  Size: $SIZE"
    echo "  Frames: $PNG_COUNT"
    echo ""
    echo "To play the video:"
    echo "  vlc $OUTPUT_FILE"
    echo "  or"
    echo "  mpv $OUTPUT_FILE"
else
    echo "✗ Error creating video"
    exit 1
fi 